/**
* @Author:wjp
* @Date:2021/1/25 1:25 下午
 */
package xerr

import (
	"encoding/json"
	"github.com/tal-tech/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

type CodeError struct {
	ErrCode int    `json:"err_code"`
	ErrMsg  string `json:"err_msg"`
}

// 属性
func (e *CodeError) GetErrCode() int {
	return e.ErrCode
}

func (e *CodeError) GetErrMsg() string {
	return e.ErrMsg
}

func (e *CodeError) Error() string {

	js, err := json.Marshal(e)
	if err != nil {
		return ""
	}

	return string(js)
}

func New(errCode int) *CodeError {

	return &CodeError{ErrCode: errCode, ErrMsg:NMapErrMsg(errCode)}
}

func NewErrCode(errCode int) *CodeError {
	return &CodeError{ErrCode: errCode}
}

func NewErrMsg(errMsg string) *CodeError {
	return &CodeError{ErrCode: 500, ErrMsg: errMsg}
}

func JsonToErr(code int, msg string) string {
	e := New(code)
	js, err := json.Marshal(e)
	if err != nil {
		return ""
	}
	return string(js)
}

func Error(err error) *CodeError {
	e := &CodeError{500, "连接失败"}
	errs, ok := status.FromError(err)
	if ok {
		errlog := json.Unmarshal([]byte(errs.Message()), e)
		if errlog != nil {
			logx.Error("错误解析失败", err)
		}
		return e
	}
	return e
}

//
func ErrorFmt(err error)*CodeError  {
	ce:=CodeError{}
	errlog := json.Unmarshal([]byte(err.Error()), &ce)
	if errlog != nil {
		logx.Error("错误解析失败", err)
	}
	if ce.ErrCode<=0{
		return &CodeError{
			ErrCode: 500,
			ErrMsg: "网络错误",
		}
	}
	return &ce
}